import axios, { AxiosInstance, AxiosRequestConfig } from 'axios'
import router from '../router/index'
import { ElMessage } from 'element-plus'
import { useStorage } from '../compositions/useStorage'

export class Axios {
   private instance: AxiosInstance
   constructor(config: AxiosRequestConfig) {
      this.instance = axios.create(config)
      this.interceptors()
   }

   private interceptors() {
      this.requestInterceptor()
      this.responseInterceptor()
   }

   public request<T, D = ResponseTypes<T>>(config: AxiosRequestConfig) {
      return new Promise(async (resolve, reject) => {
         try {
            const res = (await this.instance.request<D>(config)) as D
            resolve(res)
         } catch (error) {
            reject(error)
         }
      }) as Promise<D>
   }

   private requestInterceptor() {
      this.instance.interceptors.request.use(
         (config) => {
            const item = useStorage<{ token: string }>('token')
            if (item.token) {
               config.headers.Authorization = item.token
            }
            return config
         },

         (error) => {
            return error
         }
      )
   }

   private responseInterceptor() {
      this.instance.interceptors.response.use(
         (response) => {
            return response
         },

         (error) => {
            if (error.response.data.statusCode == '401') {
               ElMessage.error('请登录')
               return router.push({ name: 'login' })
            }
            if (error.response.data.statusCode == '429') {
               return ElMessage.error('访问速率过高')
            }
            ElMessage.error(error.response.data.message)
            return Promise.reject(error)
         }
      )
   }
}
